import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Login from "../views/Login";
import Index from "@/views/Index"
import UserCenter from "@/views/sys/UserCenter";
import store from '../store'
import request from "@/axios";
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    children:[
      {
        name: 'Index',
        component: Index ,
        path: '/index',
      },
      // {
      //   name: 'SysUser',
      //   component: User ,
      //   path: '/sys/user',
      // },
      // {
      //   name: 'SysRole',
      //   component: Role ,
      //   path: '/sys/role',
      // },
      // {
      //   name: 'SysMenu',
      //   component: Menu ,
      //   path: '/sys/menu',
      // },
      {
        name: 'SysUserCenter',
        component: UserCenter ,
        path: '/sys/user_center',
        meta:{
          title:'个人中心'
        }
      },
    ]
  },
  {
    path:'/login',
    name:'Login',
    component: Login
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to,from,next)=>{
  if(to.name==="Login"){

  }else {
    let hasRoute = store.state.menu.hasRouter
    if (!hasRoute) {
      request.get("/api/sys/menu/getMenuList").then(res => {
        //拿到菜单数据
        store.commit('setMenuList', res.data.menuList)

        //拿到用户权限
        store.commit('setPermissions', res.data.permissions)
        //动态绑定路由
        let newRouter = router.options.routes//现有的路由

        res.data.menuList.forEach(menu => {
          if (menu.children) {
            menu.children.forEach(e => {
              //转换成路由
              let router = menuToRouter(e)
              //把路由添加到路由管理中
              if (router) {
                newRouter[0].children.push(router)
              }
            })
          }
        })

        router.addRoutes(newRouter)
        let hasRouter = true
        store.commit('changeRouterStatus', hasRouter)
      })
    }

  }
  next()

})
const menuToRouter=(menu)=>{
  if(!menu.component){
    return null;
  }
  let router={
    name:'Sys'+menu.component,
    path:'/sys/'+menu.component,
    component:()=>import('@/views/sys/'+menu.component+'.vue'),
    meta:{
      title:menu.name
    }
  }
  return router
}
export default router
